<?php

namespace App\Repositories\Article;

use App\Models\Article\Category;
use App\Repositories\Repository;
use App\Services\CategoryService;
use Illuminate\Support\Facades\Redis;


/**
 *
 */
class CategoryRepository extends Repository
{
    private $redisKey ="";
    private $catService = "";

    public function __construct()
    {
        $this->redisKey =  config('rediskey.article.category');
        $this->catService = new CategoryService();
    }

    public function list()
    {
        $categorys = Redis::get($this->redisKey);
        if(!$categorys){
            $categorys = Category::get()->toArray();
            if($categorys){
                $categorys = $this->catService->getTree($categorys);
                $categorys = $this->catService->setArrayKey($categorys);
                $categorys = json_encode($categorys);
                Redis::set($this->redisKey,$categorys);
            }else{
                return false;
            }
        }

        return json_decode($categorys);
    }

    public function show($id)
    {
        $categorys = Redis::get($this->redisKey);
        if($categorys){
            $categorys = json_decode($categorys,true);
            $category = $categorys[$id];
        }else{
            $category = Category::where("id", "=", $id)->first();
        }
        $data =["categorys"=>$categorys,"category"=>$category];
        return $data;
    }

    public function store($data)
    {
        try {
            Category::create($data);
            Redis::del($this->redisKey);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }

    public function save($data)
    {
        $category = Category::find($data['id']);
        if($category){
            try {
                $category->fill($data)->save();
                Redis::del($this->redisKey);
                return $this->respondSuccess();
            } catch (\Exception $e) {
                return $this->respondError(10106);
            }
        }
        return $this->respondError(10106);
    }

    public function del($id)
    {
        $menus = Category::get()->toArray();
        $had = $this->catService->haveChild($id, $menus);
        if ($had) {
            return $this->respondError(10602);
        }

        try {
            Category::where("id", "=", $id)->delete();
            Redis::del($this->redisKey);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10107);
        }
    }



    /*
     * ==========================================================================================
     *                                    私有方法
     * ==========================================================================================
    */

}

